package com.itany.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;

@WebServlet("/form")
public class FormServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        /**
         * 获取请求中的数据
         */
        // 对于post请求方式的中文乱码
        req.setCharacterEncoding("utf-8");

        String username = req.getParameter("username");
        String password = req.getParameter("password");
        int age = Integer.parseInt(req.getParameter("age"));
        String[] hobbies = req.getParameterValues("hobbies");
        String contextPath = req.getContextPath();
        String servletPath = req.getServletPath();
        String method = req.getMethod();
        String remoteAddr = req.getRemoteAddr();

        System.out.println(username);
        System.out.println(password);
        System.out.println(age);
        System.out.println(Arrays.toString(hobbies));
        System.out.println(contextPath);
        System.out.println(servletPath);
        System.out.println(method);
        System.out.println(remoteAddr);

        // 设置响应的内容类型及编码
        resp.setContentType("text/html;charset=utf8");
        PrintWriter out = resp.getWriter();

        // 判断用户名和密码是否正确
        if("admin".equals(username) && "123".equals(password)){
            // out.print("恭喜你，登陆成功！");

            // 使用 重写向 跳转到另一个页面
            resp.sendRedirect(req.getContextPath()+"/WEB-INF/success.html");
        }else{
            // out.print("登陆失败，用户名或密码不正确！");

            // resp.sendRedirect("fail.html");
            // 使用 转发 跳转到另一个页面
            req.getRequestDispatcher("/WEB-INF/fail.html").forward(req,resp);
        }

        out.close();

    }

}
